<template>
  <el-dialog v-model="visible" width="420px" :close-on-click-modal="false" class="cmd-center-dialog">
    <template #title>
      <div class="cmd-center-title">
        <i class="el-icon-s-operation cmd-center-icon"></i>
        <span>快捷指令中心</span>
      </div>
    </template>
    <el-form label-width="80px" @submit.prevent="handleSend">
      <el-form-item label="选择网关">
        <el-select v-model="selectedGatewayId" placeholder="请选择网关" style="width: 100%;">
          <el-option
            v-for="gateway in gatewayList"
            :key="gateway.id"
            :label="`${gateway.name} (${gateway.ip})`"
            :value="gateway.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择指令">
        <el-select v-model="selectedCmd" placeholder="请选择要发送的指令" style="width: 100%" @change="onCmdSelect" value-key="type">
          <el-option v-for="item in cmdTemplates" :key="item.type" :label="item.label" :value="item" />
        </el-select>
      </el-form-item>

      <div v-if="selectedCmd">
        <el-form-item v-if="selectedCmd.params.includes('id') && !(selectedCmd.type === 'add' && addDeviceMode)" label="设备ID">
          <el-input-number v-model="userInputs.id" :min="1" :max="99" placeholder="1-99" style="width: 100%;" />
        </el-form-item>
        <el-form-item v-if="selectedCmd && selectedCmd.type === 'add'">
          <el-radio-group v-model="addDeviceMode" size="small">
            <el-radio-button label="manual">手动分配ID</el-radio-button>
            <el-radio-button label="auto">自动分配ID</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="selectedCmd && selectedCmd.type === 'add' && addDeviceMode === 'manual' && selectedCmd.params.includes('id')" label="设备ID">
          <el-input-number v-model="userInputs.id" :min="1" :max="99" placeholder="1-99" style="width: 100%;" />
        </el-form-item>
        <el-form-item v-if="selectedCmd && selectedCmd.type === 'add' && addDeviceMode === 'manual'" label="设备ESN">
          <el-input v-model="userInputs.esn" placeholder="请输入设备ESN (例如: FF0100001111)" />
        </el-form-item>
        <el-form-item v-if="selectedCmd && selectedCmd.type === 'add' && addDeviceMode === 'auto'" label="设备ESN">
          <el-button @click="fetchPendingEsns" :loading="pendingEsnLoading" size="small">查询待加入ESN</el-button>
          <el-select v-model="userInputs.esn" placeholder="请选择待加入ESN" style="width: 100%; margin-top: 8px;">
            <el-option v-for="esn in pendingEsnList" :key="esn" :label="esn" :value="esn" />
          </el-select>
        </el-form-item>
        <!-- 其它指令动态生成用户输入字段 -->
        <template v-if="!(selectedCmd.type === 'add')">
          <el-form-item 
            v-for="input in selectedCmd?.userInputs" 
            :key="input.key" 
            :label="input.label"
          >
            <el-input 
              v-if="input.type === 'text'" 
              v-model="userInputs[input.key]" 
              :placeholder="input.placeholder"
            />
            <el-input-number 
              v-else-if="input.type === 'number'" 
              v-model="userInputs[input.key]" 
              :min="input.min" 
              :max="input.max" 
              :placeholder="input.placeholder" 
              style="width: 100%;"
            />
          </el-form-item>
        </template>
      </div>

      <el-form-item class="center-btn">
        <el-button type="primary" @click="handleSend" :loading="sending" :disabled="!selectedCmd">发送</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="showDeviceStats = true"
          class="stats-btn"
          style="width: 100%;"
        >
          设备统计
        </el-button>
      </el-form-item>

      <el-form-item v-if="cmdResult" label="结果">
        <el-alert :title="cmdResult" type="success" show-icon :closable="false" style="overflow-x: auto; word-break: keep-all;" />
      </el-form-item>
    </el-form>
    <el-drawer
      v-model="showDeviceStats"
      title="设备状态统计"
      direction="rtl"
      size="900px"
      :with-header="true"
    >
      <DeviceStatsCard :ws="wsInstance?.websocketInstance ?? null" />
    </el-drawer>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { gatewayStore } from '../../store/gateway';
import { storeToRefs } from 'pinia';
import DeviceStatsCard from '../DeviceStatsCard.vue';

const showDeviceStats = ref(false);

const props = defineProps({
  modelValue: Boolean,
  sendCmd: Function,
  isPaused: Boolean,
  currentGatewayId: {
    type: Number,
    default: 1
  }
});
const emit = defineEmits(['update:modelValue', 'cmd-result', 'toggle-pause', 'update:currentGatewayId']);

const visible = ref(props.modelValue);
watch(() => props.modelValue, v => (visible.value = v));
watch(visible, v => emit('update:modelValue', v));

const gateway_store = gatewayStore();
const { gatewayList } = storeToRefs(gateway_store);

const selectedGatewayId = ref(props.currentGatewayId);
watch(() => props.currentGatewayId, (newVal) => {
  selectedGatewayId.value = newVal;
});
watch(selectedGatewayId, (newVal) => {
  emit('update:currentGatewayId', newVal);
});

onMounted(async () => {
  // 获取网关列表
  await gateway_store.fetchGatewayList();
});

interface CommandTemplate {
  label: string;
  type: string;
  params: string[];
  userInputs?: {
    key: string;
    label: string;
    type: 'text' | 'number';
    placeholder?: string;
    min?: number;
    max?: number;
  }[];
}

const cmdTemplates: CommandTemplate[] = [
  { label: '查询所有设备', type: 'queryAll', params: [] },
  { label: '查询网关ID', type: 'queryGateway', params: [] },
  { 
    label: '添加设备', 
    type: 'add', 
    params: ['id', 'esn'],
    userInputs: [
      { key: 'esn', label: '设备ESN', type: 'text', placeholder: '请输入设备ESN (例如: FF0100001111)' }
    ]
  },
  { label: '删除设备', type: 'delete', params: ['id'] },
  { label: '重启设备', type: 'device_reboot', params: ['id'] },
  { label: '查询版本', type: 'queryVersion', params: ['id'] },
  { label: '查询电路增益', type: 'queryCircuitGain', params: ['id'] },
  { 
    label: '设置电路增益', 
    type: 'setCircuitGain', 
    params: ['id', 'gain'],
    userInputs: [
      { key: 'gain', label: '增益值', type: 'number', placeholder: '增益值(1~700)', min: 1, max: 700 }
    ]
  },
  { label: '查询设备类型', type: 'queryDeviceType', params: ['id'] },
  // 新增滤波器系数相关指令
  { label: '查询滤波器系数', type: 'queryFilterRatio', params: ['id'] },
  { 
    label: '设置滤波器系数', 
    type: 'setFilterRatio', 
    params: ['id', 'ratio'],
    userInputs: [
      { key: 'ratio', label: '滤波器系数', type: 'number', placeholder: '0.1~10.0', min: 0.1, max: 10.0 }
    ]
  },
  // 新增：紫外检测阈值查询
  {
    label: '查询紫外检测阈值',
    type: 'queryUvThreshold',
    params: ['queryId'],
    userInputs: [
      { key: 'queryId', label: '设备ID', type: 'number', placeholder: '50~10000', min: 50, max: 10000 }
    ]
  },
  // 新增：紫外检测阈值设置
  {
    label: '设置紫外检测阈值',
    type: 'setUvThreshold',
    params: ['id', 'threshold'],
    userInputs: [
      { key: 'id', label: '设备ID', type: 'number', placeholder: '50~10000', min: 50, max: 10000 },
      { key: 'threshold', label: '紫外阈值', type: 'number', placeholder: '50~10000', min: 50, max: 10000 }
    ]
  },
];

const selectedCmd = ref<CommandTemplate | null>(null);
const userInputs = reactive<{ [key: string]: any }>({});

const sending = ref(false);
const cmdResult = ref('');

const addDeviceMode = ref<'manual' | 'auto'>('manual');
const pendingEsnList = ref<string[]>([]);
const pendingEsnLoading = ref(false);

function fetchPendingEsns() {
  if (!selectedGatewayId.value) {
    return ElMessage.error('请选择网关');
  }
  pendingEsnLoading.value = true;
  pendingEsnList.value = [];
  // 发送WebSocket请求
  if (props.sendCmd) {
    props.sendCmd(JSON.stringify({
      action: "gateway",
      type: 'queryPendingDevices',
      gatewayId: gatewayList.value.find(g => g.id === selectedGatewayId.value)?.ip
    })).then((result: string) => {
      try {
        console.log('查询结果:', result);
        const res = typeof result === 'string' ? JSON.parse(result) : result;
        if (res && res.success && Array.isArray(res.response)) {
          pendingEsnList.value = res.response;
        } else {
          ElMessage.warning(res.message || '未获取到待加入ESN列表');
        }
      } catch (e) {
        console.error(e);
        ElMessage.error('解析ESN列表失败');
      }
    }).finally(() => {
      pendingEsnLoading.value = false;
    });
  } else {
    ElMessage.warning('发送功能未初始化');
    pendingEsnLoading.value = false;
  }
}

function onCmdSelect() {
  // 重置用户输入
  Object.keys(userInputs).forEach(key => {
    delete userInputs[key];
  });
  cmdResult.value = '';
  // 新增：切换添加设备模式时重置
  if (selectedCmd.value && selectedCmd.value.type === 'add') {
    addDeviceMode.value = 'manual';
    pendingEsnList.value = [];
  }
}

function togglePause() {
  emit('toggle-pause');
}

async function handleSend() {
  if (!selectedCmd.value) return;

  // 验证网关选择
  if (!selectedGatewayId.value) {
    return ElMessage.error('请选择网关');
  }

  // 获取选中的网关信息
  const selectedGateway = gatewayList.value.find(g => g.id === selectedGatewayId.value);
  if (!selectedGateway) {
    return ElMessage.error('选中的网关不存在');
  }

  // 新增：添加设备自动/手动模式参数处理
  if (selectedCmd.value.type === 'add') {
    if (addDeviceMode.value === 'manual') {
      if (!userInputs.id) return ElMessage.error('设备ID不能为空');
      if (!userInputs.esn) return ElMessage.error('设备ESN不能为空');
    } else if (addDeviceMode.value === 'auto') {
      if (!userInputs.esn) return ElMessage.error('请选择待加入ESN');
    }
  }

  // 验证必填参数
  const payload: { [key: string]: any } = {
    action: 'gateway',
    type: selectedCmd.value.type,
    gatewayId: selectedGateway.ip
  };
  
  for (const param of selectedCmd.value.params) {
    // 新增：自动模式下不传id
    if (selectedCmd.value.type === 'add' && addDeviceMode.value === 'auto' && param === 'id') continue;
    if (userInputs[param] === undefined || userInputs[param] === '') {
      return ElMessage.error(`参数 ${param} 不能为空`);
    }
    payload[param] = userInputs[param];
  }

  // 新增：处理滤波器系数相关AT指令拼接
  let atCmd = '';
  if (selectedCmd.value.type === 'queryFilterRatio') {
    atCmd = `AT+ATCMD=${userInputs.id},AT+FRAT?\r\n`;
  } else if (selectedCmd.value.type === 'setFilterRatio') {
    // 校验ratio范围
    const ratio = Number(userInputs.ratio);
    if (isNaN(ratio) || ratio < 0.1 || ratio > 10.0) {
      return ElMessage.error('滤波器系数必须在0.1~10.0之间');
    }
    atCmd = `AT+ATCMD=${userInputs.id},AT+FRAT=${ratio}\r\n`;
  }
  if (selectedCmd.value.type === 'queryUvThreshold') {
    atCmd = `AT+ATCMD=${userInputs.queryId},AT+FATH?\r\n`;
  } else if (selectedCmd.value.type === 'setUvThreshold') {
    // 校验范围
    const threshold = Number(userInputs.threshold);
    if (isNaN(threshold) || threshold < 50 || threshold > 10000) {
      return ElMessage.error('紫外阈值必须在50~10000之间');
    }
    atCmd = `AT+ATCMD=${userInputs.id},AT+FATH=${threshold}\r\n`;
  }
  if (atCmd) {
    payload.atCmd = atCmd;
  }

  sending.value = true;
  cmdResult.value = '';

  try {
    // 统一所有指令的发送方式，全部通过 JSON 格式发送
    const result = await props.sendCmd(JSON.stringify(payload));
      console.log(result)
      if (result) {
        let displayResult = result;
        try {
          const parsedResult = typeof result === 'string' ? JSON.parse(result) : result;
          displayResult = JSON.stringify(parsedResult, null, 2);
        } catch (parseError) {
          console.warn('结果不是有效的JSON，直接显示原始结果:', result);
        }
        cmdResult.value = displayResult;
        emit('cmd-result', result);
        ElMessage.success('指令发送成功');
      } else {
        ElMessage.warning('未收到响应');
      }
  } catch (e) {
    const errorMsg = '发送失败：' + (e as Error).message;
    cmdResult.value = errorMsg;
    ElMessage.error(errorMsg);
  } finally {
    sending.value = false;
  }
}



watch(cmdResult, (val) => {
  if (selectedCmd.value && selectedCmd.value.label === '删除设备' && val) {
    let res
    try {
      res = typeof val === 'string' ? JSON.parse(val) : val
    } catch (e) {
      res = val
    }
    if (res && res.success) {
      // 假设后端返回res.id和res.esn，否则用本地参数
      cmdResult.value = `删除成功，设备ID: ${res.id || userInputs.id}，ESN: ${res.esn || userInputs.esn}`
    }
  }
})
</script>

<style scoped>
.el-dialog {
  border-radius: 14px;
}
.cmd-center-title {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  font-weight: bold;
  color: #1890ff;
  gap: 10px;
}
.cmd-center-icon {
  font-size: 32px;
  color: #1dc8e9;
  filter: drop-shadow(0 2px 8px #1de9b6aa);
}
.cmd-center-dialog >>> .el-dialog__header {
  border-bottom: none;
}
.center-btn .el-form-item__content {
  display: flex;
  justify-content: center !important;
}
.stats-btn {
  background: linear-gradient(135deg, #1de9b6 0%, #1dc8e9 100%) !important;
  color: #fff !important;
  border: none !important;
  border-radius: 8px !important;
  font-weight: bold;
  font-size: 18px;
  box-shadow: 0 2px 8px rgba(0,255,255,0.15);
  transition: all 0.2s;
}
.stats-btn:hover, .stats-btn:focus {
  background: linear-gradient(135deg, #1dc8e9 0%, #1de9b6 100%) !important;
  color: #ffe066 !important;
  box-shadow: 0 4px 16px rgba(0,255,255,0.25);
}
</style>